package com.sleep.psy.external_server.business.adjustment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sleep.psy.external_server.business.adjustment.entity.AdjustmentPlan;
import com.sleep.psy.external_server.business.adjustment.entity.AdjustmentPlanDetails;
import com.sleep.psy.external_server.business.adjustment.entity.vo.GenerateSleepPlanReq;
import com.sleep.psy.external_server.business.adjustment.mapper.AdjustmentPlanMapper;
import com.sleep.psy.external_server.business.adjustment.service.AdjustmentPlanDetailsService;
import com.sleep.psy.external_server.business.adjustment.service.AdjustmentPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sleep.psy.external_server.business.evaluation.entity.EvaluationRecord;
import com.sleep.psy.external_server.business.evaluation.entity.EvaluationReport;
import com.sleep.psy.external_server.business.evaluation.entity.dto.Res;
import com.sleep.psy.external_server.business.evaluation.service.EvaluationRecordService;
import com.sleep.psy.external_server.business.evaluation.service.EvaluationReportService;
import com.sleep.psy.external_server.business.main.entity.MainScheme;
import com.sleep.psy.external_server.business.main.entity.MainUserScheme;
import com.sleep.psy.external_server.business.main.entity.dto.SchemeInfo;
import com.sleep.psy.external_server.business.main.service.MainUserSchemeService;
import com.sleep.psy.external_server.business.main.service.MainUserService;
import com.sleep.psy.external_server.constants.MySqlConstant;
import com.sleep.psy.external_server.property.SleepProperties;
import com.sleep.psy.external_server.result.Result;
import com.sleep.psy.external_server.result.ResultEnum;
import com.sleep.psy.external_server.result.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 调节方案 服务实现类
 * </p>
 *
 * @author wenliguo
 * @since 2025-08-12
 */
@Service
public class AdjustmentPlanServiceImpl extends ServiceImpl<AdjustmentPlanMapper, AdjustmentPlan> implements AdjustmentPlanService {

    protected Logger logger = LoggerFactory.getLogger(AdjustmentPlanService.class);

    @Autowired
    private EvaluationRecordService evaluationRecordService;

    @Autowired
    private EvaluationReportService evaluationReportService;

    @Autowired
    private AdjustmentPlanDetailsService adjustmentPlanDetailsService;

    @Autowired
    private AdjustmentPlanMapper adjustmentPlanMapper;

    @Autowired
    private SleepProperties sleepProperties;

    @Autowired
    private MainUserSchemeService userSchemeService;

    /**
     * 生成条件方案
     * @author wenliguo
     * @date 2025/6/10 14:54
     * @param req 请求参数
     * @return com.sleep.psy.main_server.result.Result
     */
    @Override
    public Result generateSleepPlan(GenerateSleepPlanReq req) {
        Long recordId = req.getRecordId();
        if (null == recordId) {
            //不存在
            List<EvaluationRecord> records = evaluationRecordService.selectRecordsByUserIdScaleId(req.getUserId(), sleepProperties.getSleepQuestionScale());
            if (records.isEmpty()) {
                return ResultUtil.error(ResultEnum.NOT_HAVE_RECORD);
            }

            ArrayList<Long> list = new ArrayList<>();
            for (EvaluationRecord record : records) {
                list.add(record.getId());
            }

            List<AdjustmentPlan> plans = selectPlans(req.getUserId(), list);
            if (plans.isEmpty()) {
                return ResultUtil.error(ResultEnum.NOT_HAVE_RECORD);
            }

            AdjustmentPlan plan = plans.get(0);
            if (null == plan) {
                return ResultUtil.error(ResultEnum.NOT_HAVE_RECORD);
            }

            List<AdjustmentPlanDetails> details = adjustmentPlanDetailsService.selectPlanDetailsByPlanId(plan.getId());
            return ResultUtil.success(details);

        }

        EvaluationRecord record = evaluationRecordService.selectRecord(req.getRecordId(), req.getUserId());
        if (null == record) {
            return ResultUtil.error(ResultEnum.NO_EVALUATION_RECORD);
        }

        EvaluationReport report = evaluationReportService.selectReport(req.getRecordId());
        if (null == report) {
            return ResultUtil.error(ResultEnum.NO_EVALUATION_REPORT);
        }

        AdjustmentPlan plan = selectPlan(req.getUserId(), req.getRecordId());
        if (null != plan) {
            List<AdjustmentPlanDetails> details = adjustmentPlanDetailsService.selectPlanDetailsByPlanId(plan.getId());
            return ResultUtil.success(details);
        }

        //生成调节方案
        AdjustmentPlan adjustmentPlan = new AdjustmentPlan();
        adjustmentPlan.setUserId(req.getUserId());
        adjustmentPlan.setRecordId(req.getRecordId());
        Integer isAutoSend = 0;
        if (null != req.getSchemeId()) {
            List<MainUserScheme> schemes = userSchemeService.selectByUserIdAndSchemeId(req.getSchemeId(), req.getUserId());
            if (schemes.isEmpty()) {
                adjustmentPlan.setStatus(MySqlConstant.STATUS_0);
            } else {
                for (MainUserScheme scheme : schemes) {
                    String schemeInfo = scheme.getSchemeInfo();
                    SchemeInfo mainScheme = JSONObject.parseObject(schemeInfo, SchemeInfo.class);
                    isAutoSend = mainScheme.getIsAutoSend();
                    if (MySqlConstant.IS_AUTO_SEND_1.equals(isAutoSend)) {
                        adjustmentPlan.setStatus(MySqlConstant.STATUS_1);
                    } else {
                        adjustmentPlan.setStatus(MySqlConstant.STATUS_0);
                    }
                }
            }
        } else {
            adjustmentPlan.setStatus(MySqlConstant.STATUS_0);
        }


        adjustmentPlanMapper.insert(adjustmentPlan);

        List<AdjustmentPlanDetails> details = adjustmentPlanDetailsService.generateSleepPlanDetail(req.getUserId(), adjustmentPlan.getId(), record, report, isAutoSend);

        return ResultUtil.success(details);

    }

    /**
     * 通过用户id和测评记录ids获取多个调节方案
     * @author wenliguo
     * @date 2025/6/17 14:55
     * @param userId 用户id
     * @param ids 测评记录列表
     * @return java.util.List<com.sleep.psy.main_server.business2.adjustment.entity.AdjustmentPlan>
     */
    @Override
    public List<AdjustmentPlan> selectPlans(Long userId, List<Long> ids) {
        QueryWrapper<AdjustmentPlan> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .in("record_id", ids)
                .eq("status", MySqlConstant.STATUS_1)
                .orderByDesc("update_time");
        return adjustmentPlanMapper.selectList(wrapper);
    }

    /**
     * 通过用户id和测评记录id获取有效的调节方案
     * @author wenliguo
     * @date 2025/6/9 11:48
     * @param userId 用户id
     * @param recordId 测评记录id
     * @return com.sleep.psy.main_server.business2.adjustment.entity.AdjustmentPlan
     */
    @Override
    public AdjustmentPlan selectPlan(Long userId, Long recordId) {
        QueryWrapper<AdjustmentPlan> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("record_id", recordId)
                .eq("status", MySqlConstant.STATUS_1);
        return adjustmentPlanMapper.selectOne(wrapper);
    }

    /**
     * 通过用户id和测评记录id获取有效的调节方案(存在计划详情)
     * @author wenliguo
     * @date 2025/8/18 10:25
     * @param userId 用户id
     * @param recordId 测评id
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result selectValidPlan(Long userId, Long recordId) {
        AdjustmentPlan plan = selectPlan(userId, recordId);
        if (null != plan) {
            List<AdjustmentPlanDetails> details = adjustmentPlanDetailsService.selectPlanDetailsByPlanId(plan.getId());
            plan.setPlanDetails(details);
        }
        return ResultUtil.success(plan);
    }

    /**
     * 通过用户id获取有效的调节方案
     * @author wenliguo
     * @date 2025/8/25 14:42
     * @param userId 用户id
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result selectValidPlanByUserId(Long userId) {
        QueryWrapper<AdjustmentPlan> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("status", MySqlConstant.STATUS_1)
                .orderByDesc("id");
        List<AdjustmentPlan> plans = adjustmentPlanMapper.selectList(wrapper);
        if (plans.isEmpty()) {
            return ResultUtil.success();
        }

        AdjustmentPlan plan = plans.get(0);
        List<AdjustmentPlanDetails> details = adjustmentPlanDetailsService.selectPlanDetailsByPlanId(plan.getId());
        return ResultUtil.success(details);
    }
}
